
const dao = require("../dao/message")
const response = require("../utils/response")
const { checkauth } = require("../utils/check");

/**
 * 发送消息
 * @param {*} data {f_user_id, secret_id, t_user_id, title, content, link}
 */
async function add_message(data) {
    let auth = await checkauth(data.secret_id, data.f_user_id);
    if (!auth) {
        return response.forbidden("权限错误");
    }
    let mid = await dao.add_message(data.f_user_id, data.t_user_id, data.title, data.content, data.link);
    return response.ok({
        message_id: mid
    })
}

/**
 * 设置已读某消息
 * @param {*} data {message_id}
 */
async function read_message(data) {
    let user_id = await dao.get_user_id(data.message_id);
    let auth = await checkauth(data.secret_id, user_id);
    if (!auth) {
        return response.forbidden("权限错误");
    }
    await dao.read_message(data.message_id);
}

/**
 * 删除某消息
 * @param {*} data {message_id}
 */
async function del_message(data) {
    let user_id = await dao.get_user_id(data.message_id);
    let auth = await checkauth(data.secret_id, user_id);
    if (!auth) {
        return response.forbidden("权限错误");
    }
    await dao.del_message(data.message_id);
}

/**
 * 删除所有已读消息
 * @param {*} data {user_id}
 */
async function del_read_message(data) {
    let auth = await checkauth(data.secret_id, data.user_id)
    if (!auth) {
        return response.forbidden("权限错误");
    }
    await dao.del_read_message(data.user_id);
}

/**
 * 获取未读数
 * @param {*} data {user_id}
 */
async function get_unread_num(data) {
    let auth = await checkauth(data.secret_id, data.user_id);
    if (!auth) {
        return response.forbidden("权限错误");
    }
    return response.ok({ count: await dao.get_unread_num(data.user_id) });
}

/**
 * 获取消息列表
 * @param {*} data {user_id}
 */
async function get_message_list(data) {
    let auth = await checkauth(data.secret_id, data.user_id)
    if (!auth) {
        return response.forbidden("权限错误");
    }
    var res = await dao.get_message_list(data.user_id);
    return response.ok(res);
}

module.exports = {
    add_message: add_message,
    read_message: read_message,
    del_message: del_message,
    del_read_message: del_read_message,
    get_unread_num: get_unread_num,
    get_message_list: get_message_list,
}
